package com.movecar.ui;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.core.GeoPoint;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.meetme.android.horizontallistview.HorizontalListView;
import com.movecar.R;
import com.movecar.adapter.AddShareGroupAdapter;
import com.movecar.adapter.AddShareGroupAdapter.ViewHolder;
import com.movecar.adapter.CustomArrayAdapter;
import com.movecar.adapter.CustomArrayAdapter.Holder;
import com.movecar.adapter.MyShareGridViewAdapter;
import com.movecar.dialog.CustomDialog;
import com.movecar.listener.BaseLocationActivity;
import com.movecar.listview.WaterFallListView;
import com.movecar.model.CloudBeansBean;
import com.movecar.model.LocationDetailBean;
import com.movecar.model.LocationDetailBean.LocationDetail;
import com.movecar.model.MyShareBean;
import com.movecar.model.OrderMessageBean;
import com.movecar.model.PlatMessageBean;
import com.movecar.pic.Bimp;
import com.movecar.pic.TestPicActivity;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.BitMapUtil;
import com.movecar.utils.Converter;
import com.movecar.utils.DataStore;
import com.movecar.utils.FileProvider;
import com.movecar.utils.HttpGetRequestAsyncTask;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;
import com.movecar.widget.MyGridView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.rockerhieu.emojicon.EmojiconEditText;
import com.rockerhieu.emojicon.EmojiconGridFragment;
import com.rockerhieu.emojicon.EmojiconTextView;
import com.rockerhieu.emojicon.EmojiconsFragment;
import com.rockerhieu.emojicon.emoji.Emojicon;

/**
 * 主页-发分享，推荐店
 * 
 * @author Zhao.JQ
 * 
 */

public class AddMyShareActivity extends BaseLocationActivity implements android.view.View.OnClickListener,
		EmojiconGridFragment.OnEmojiconClickedListener, EmojiconsFragment.OnEmojiconBackspaceClickedListener,
		RequestResultCallback {

	private EmojiconEditText share_info;
	private InputMethodManager imm;
	private Button share, back, camera, album, emojicons_button, next1, location;
	private CustomProgressDialog progressDialog = null;
	private MyGridView mGrideView;// 添加照片
	private MyShareGridViewAdapter mGridViewAdapter;
	final List<String> pathList = new ArrayList<String>();
	private ArrayList<Bitmap> bitmapList = new ArrayList<Bitmap>();
	// private List<Bitmap> upLoadPicList = new ArrayList<Bitmap>();
	private ArrayList<String> dataList = new ArrayList<String>();
	// private DataAdapter dataAdapter;
	private String messageId;
	private boolean isCheck = false;
	private boolean isGroupCheck = false;
	private TextView chCounterText, explain_title, explain, second_explain_title, second_explain;
	private HorizontalListView mHlvCustomListWithDividerAndFadingEdge;
	private HorizontalListView share_HorizontalListView;
	private PlatMessageBean mPlatMessageBean;
	private List<PlatMessageBean> mPlatMessageBeanList = new ArrayList<PlatMessageBean>();
	private CustomArrayAdapter adapter;
	private List<OrderMessageBean> mOrderMessageBeanList;
	private OrderMessageBean mOrderMessageBean;
	private AddShareGroupAdapter mAddShareGroupAdapter;
	public Map<Integer, Boolean> isChecked;
	private RelativeLayout share_info_relative, finish_share_relative, explain_relative, second_explain_relative,
			recommend_name_relative;
	private EmojiconTextView share_content;
	private ImageView share_img;
	private String uploadInfo_messageId;
	private MyShareBean mMyShareBean;
	private CloudBeansBean mCloudBeansBean;
	/* 确定删除图片的标记 */
	private int delNum;
	/* 确定删除图片 */
	private static final int YES = -1;
	/* 取消删除图片 */
	private static final int NO = -2;
	/* 选择图片 */
	private static final int PICK = 0x11;
	/* 切割图片 */
	private static final int CROP = 0x12;
	/* 获取地址信息 */
	private static final int LOCATION = 0x13;
	/** 新相片文件 */
	private File rFilePicture = null;
	/** 相片临时文件 */
	private File rFileTemporary = null;
	private final ArrayList<String> mListImageFile = new ArrayList<String>();
	private String MessageId, isRelate;
	private LinearLayout emojicons_linear;
	private String platMessageId;
	private boolean shareCheck;
	private String ThemeId = "0";
	private String ShareTitle, ShareContent, SharePic;// 现场活动
	private int checkPosition;
	private int checkPositionPlat = -1;
	private ImageLoader imageLoader = null;
	private EditText recommend_name;
	private String sectionName = "", sectionCity = "", sectionLocation = "";

	private GeoPoint mlocation;
	private String address;
	private String keyword;

	String apiUrl = "http://api.dianping.com/v1/business/find_businesses";
	private LocationDetailBean mLocationDetailBean;
	private List<LocationDetail> mDataList;
	private List<LocationDetail> resultList = new ArrayList<LocationDetail>();
	private DataAdapter dataAdapter;
	private int pageNo = 1;
	protected WaterFallListView mXList;// 地址列表
	private boolean flgMore = false;
	private ImageView shop;
	private File file;
	private List<File> fileList = new ArrayList<File>();
	private String sectionId = "0";// 现场活动用
	private String TdcId = "0";
	private int shareFlag;
	private View mainView;
	private LayoutInflater layoutInflater;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mainView = layoutInflater.inflate(R.layout.add_my_share, null);
		setContentView(mainView);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		// 从订单列表跳转过来
		MessageId = getIntent().getStringExtra("MessageId");
		// 1：有活动 0：没活动(推荐店)
		isRelate = getIntent().getStringExtra("isRelate");
		// 主题ID(去沾光)
		ThemeId = getIntent().getStringExtra("ThemeId");
		// 活动ID(去沾光)
		messageId = getIntent().getStringExtra("messageId");
		// 现场活动
		TdcId = getIntent().getStringExtra("TdcId");
		sectionId = getIntent().getStringExtra("sectionId");
		sectionName = getIntent().getStringExtra("sectionName");

		ShareTitle = getIntent().getStringExtra("ShareTitle");
		ShareContent = getIntent().getStringExtra("ShareContent");
		SharePic = getIntent().getStringExtra("SharePic");

		shareFlag = getIntent().getIntExtra("shareFlag", 1);
		requestLocation();
		initView();
	}

	private void initView() {
		imageLoader = ImageLoader.getInstance();
		// 搜索列表
		mXList = (WaterFallListView) findViewById(R.id.location_list);
		mXList.setPullRefreshEnable(false);
		mXList.setPullLoadEnable(false);
		dataAdapter = new DataAdapter(this);
		mXList.setAdapter(dataAdapter);
		// 推荐店icon
		shop = (ImageView) findViewById(R.id.shop);
		// 水印选择说明
		explain_relative = (RelativeLayout) findViewById(R.id.explain_relative);
		// 水印选择说明标题
		explain_title = (TextView) findViewById(R.id.explain_title);
		// 水印选择说明内容
		explain = (TextView) findViewById(R.id.explain);
		// 活动选择说明
		second_explain_relative = (RelativeLayout) findViewById(R.id.second_explain_relative);
		// 活动选择说明标题
		second_explain_title = (TextView) findViewById(R.id.second_explain_title);
		// 活动选择说明内容
		second_explain = (TextView) findViewById(R.id.second_explain);

		// 分享内容relative
		share_info_relative = (RelativeLayout) findViewById(R.id.share_info_relative);

		// 分享完成图片和文字
		finish_share_relative = (RelativeLayout) findViewById(R.id.finish_share_relative);
		// 水印选择
		mHlvCustomListWithDividerAndFadingEdge = (HorizontalListView) findViewById(R.id.hlvCustomListWithDividerAndFadingEdge);
		// 活动选择
		share_HorizontalListView = (HorizontalListView) findViewById(R.id.share_HorizontalListView);
		// 字数限制
		chCounterText = (TextView) findViewById(R.id.text_count);
		// 推荐店输入框
		recommend_name = (EditText) findViewById(R.id.recommend_name);
		recommend_name.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				mXList.setVisibility(View.GONE);
				if (s.length() > 2 && sectionName == null) {
					// 读取数据
					SharedPreferences preferences = getSharedPreferences("my_location", 0);
					address = preferences.getString("address", "");

					keyword = s.toString();
					getLocationInfo(preferences.getString("latitude", ""), preferences.getString("longitude", ""));
				} else {
					if (s.length() > 2 && !sectionName.equals(s.toString())) {
						// 读取数据
						SharedPreferences preferences = getSharedPreferences("my_location", 0);
						address = preferences.getString("address", "");

						keyword = s.toString();
						getLocationInfo(preferences.getString("latitude", ""), preferences.getString("longitude", ""));
					}
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {

				// TODO Auto-generated method stub

			}
		});
		recommend_name_relative = (RelativeLayout) findViewById(R.id.recommend_name_relative);

		back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		next1 = (Button) findViewById(R.id.next1);
		next1.setOnClickListener(this);
		share = (Button) findViewById(R.id.share);
		share.setOnClickListener(this);
		camera = (Button) findViewById(R.id.camera);
		camera.setOnClickListener(this);
		album = (Button) findViewById(R.id.album);
		album.setOnClickListener(this);
		// 表情按钮
		emojicons_button = (Button) findViewById(R.id.emojicons_button);
		emojicons_button.setOnClickListener(this);
		// 表情列表
		emojicons_linear = (LinearLayout) findViewById(R.id.emojicons_linear);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("发表分享");
		// 完成分享图片
		share_img = (ImageView) findViewById(R.id.share_img);
		// 完成分享内容
		share_content = (EmojiconTextView) findViewById(R.id.share_content);
		// 分享位置按钮
		location = (Button) findViewById(R.id.location);
		location.setVisibility(View.VISIBLE);
		location.setOnClickListener(this);
		// 分享内容输入框
		share_info = (EmojiconEditText) findViewById(R.id.share_info);
		share_info.setEmojiconSize(Converter.dp2pixel(AddMyShareActivity.this, 20));
		share_info.setOnClickListener(this);
		share_info.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable s) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				String content = share_info.getText().toString();
				if (content.length() > 300) {
					chCounterText.setTextColor(Color.RED);
				} else {
					chCounterText.setTextColor(R.color.text_black1);
				}
				chCounterText.setText(content.length() + "/" + "300");
			}

		});
		// 相片Gridview
		mGrideView = (MyGridView) findViewById(R.id.edit_photo_grid);
		mGrideView.setSelector(new ColorDrawable(Color.TRANSPARENT));

		mGridViewAdapter = new MyShareGridViewAdapter(this, new ArrayList<Bitmap>());
		if (dataList.size() == 0) {
			mGrideView.setVisibility(View.GONE);
		}
		mGrideView.setAdapter(mGridViewAdapter);
		// 添加删除图片监听
		mGrideView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(final AdapterView<?> arg0, final View arg1, final int arg2, final long arg3) {
				delNum = arg2;
				CustomDialog.Builder customBuilder = new CustomDialog.Builder(AddMyShareActivity.this);
				ImageView img = new ImageView(AddMyShareActivity.this);
				img.setImageResource(R.drawable.ic_launcher);
				customBuilder.setImgIcon(img).setMessage("是否删除图片")

				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						AddMyShareActivity.this.bitmapList.remove(delNum);
						fileList.remove(delNum);
						mGridViewAdapter.notifyDataSetChanged();
						dialog.dismiss();

					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						dialog.dismiss();

					}
				});
				customBuilder.create().show();

			}
		});

		if ("0".equals(isRelate)) {
			shareFlag = 1;
			queryPlat();
			isWatermarkVisibale();

		} else if ("1".equals(isRelate)) {
			shareFlag = 0;
			back.setVisibility(View.VISIBLE);
			isWatermarkVisibale();
			queryPlat();

		} else {
			back.setVisibility(View.VISIBLE);
			isWatermarkVisibale();
			queryPlat();
		}

	}

	@Override
	public void onLocation(final GeoPoint location, final String address) {

		super.onLocation(location, address);

		this.mlocation = location;
		this.address = address;

		SharedPreferences preferences = getSharedPreferences("my_location", 0);
		// 获得可编辑对象
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString("address", address);
		editor.putString("latitude", String.valueOf(location.getLatitudeE6() / 1E6));
		editor.putString("longitude", String.valueOf(location.getLongitudeE6() / 1E6));
		editor.commit();

	}

	/**
	 * 分享选择水印
	 * 
	 */
	public void isWatermarkVisibale() {

		next1.setVisibility(View.VISIBLE);
		share_info_relative.setVisibility(View.VISIBLE);
		mHlvCustomListWithDividerAndFadingEdge.setVisibility(View.VISIBLE);
		explain_relative.setVisibility(View.VISIBLE);

		share_HorizontalListView.setVisibility(View.GONE);
		finish_share_relative.setVisibility(View.GONE);
		second_explain_relative.setVisibility(View.GONE);
		share.setVisibility(View.GONE);

	}

	/**
	 * 分享选择活动标签
	 * 
	 */
	public void isGroupVisibale() {

		next1.setVisibility(View.GONE);
		share_info_relative.setVisibility(View.GONE);
		mHlvCustomListWithDividerAndFadingEdge.setVisibility(View.GONE);
		explain_relative.setVisibility(View.GONE);

		finish_share_relative.setVisibility(View.VISIBLE);
		share.setVisibility(View.VISIBLE);
		second_explain_relative.setVisibility(View.VISIBLE);
		share_HorizontalListView.setVisibility(View.VISIBLE);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_left:
			if (share.getVisibility() == View.VISIBLE) {
				isWatermarkVisibale();
				recommend_name_relative.setVisibility(View.GONE);
				shop.setVisibility(View.GONE);

				if (mPlatMessageBeanList.size() == 0) {
					explain_relative.setVisibility(View.INVISIBLE);
				} else {
					explain_relative.setVisibility(View.VISIBLE);
					explain_title.setText(mPlatMessageBean.getDesTitle());
					explain.setText(mPlatMessageBean.getDesContent());
				}

			} else {
				imm.hideSoftInputFromWindow(share_info.getWindowToken(), 0);
				finish();
			}

			break;
		case R.id.next1:

			if ("".equals(share_info.getText().toString().trim())) {
				Alert.error(AddMyShareActivity.this, "内容不能为空！");
			} else if (share_info.getText().toString().trim().length() > 300) {
				Alert.error(AddMyShareActivity.this, "内容长度超出限制！");
			} else if (bitmapList.size() <= 0) {
				Alert.error(AddMyShareActivity.this, "请上传图片！");
			} else {

				if (shareFlag == 0) {
					getOrderMsg();
					Bitmap bitmap = ThumbnailUtils.extractThumbnail(bitmapList.get(0), 240, 240);
					share_content.setText(share_info.getText());
					share_img.setImageBitmap(bitmap);
				} else if (shareFlag == 1) {

					isGroupVisibale();
					Bitmap bitmap = ThumbnailUtils.extractThumbnail(bitmapList.get(0), 240, 240);
					share_content.setText(share_info.getText());
					share_img.setImageBitmap(bitmap);
					share_HorizontalListView.setVisibility(View.GONE);
					second_explain_title.setText("推荐");
					second_explain.setText("分享店铺给小伙伴吧！");
					recommend_name_relative.setVisibility(View.VISIBLE);
					recommend_name.setText(sectionName == null ? "" : sectionName);
					shop.setVisibility(View.VISIBLE);

				} else {

				}

			}

			break;

		case R.id.camera:
			emojicons_linear.setVisibility(View.GONE);
			if (fileList.size() >= 6) {
				Alert.warn(this, "只能上传6张照片");
				return;
			}
			try {

				String SDState = Environment.getExternalStorageState();
				if (SDState.equals(Environment.MEDIA_MOUNTED)) {
					rFilePicture = FileProvider.getNewJpegFile();
					final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(rFilePicture));
					intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
					intent.putExtra("return-data", true);
					startActivityForResult(intent, AddMyShareActivity.PICK);
				} else {
					Alert.error(this, "内存卡不存在");
				}

			} catch (final IOException e) {
				Alert.error(this, "无法完成拍照操作，请检查存储卡是否安装或空间已满。");
				rFilePicture = null;
			}

			break;
		case R.id.album:
			emojicons_linear.setVisibility(View.GONE);
			mHlvCustomListWithDividerAndFadingEdge.setVisibility(View.VISIBLE);
			explain_relative.setVisibility(View.VISIBLE);
			if (fileList.size() >= 6) {
				Alert.warn(this, "只能上传6张照片");
				return;
			}
			Intent intent = new Intent(AddMyShareActivity.this, TestPicActivity.class);
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("dataList", getIntentArrayList(dataList));
			intent.putExtras(bundle);
			startActivityForResult(intent, 0);
			break;

		case R.id.emojicons_button:
			if (emojicons_linear.getVisibility() == View.VISIBLE) {
				mHlvCustomListWithDividerAndFadingEdge.setVisibility(View.VISIBLE);
				explain_relative.setVisibility(View.VISIBLE);
				emojicons_linear.setVisibility(View.GONE);
				emojicons_button.setBackgroundResource(R.drawable.emoji);
			} else {

				imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
				emojicons_linear.setVisibility(View.VISIBLE);
				mHlvCustomListWithDividerAndFadingEdge.setVisibility(View.GONE);
				explain_relative.setVisibility(View.GONE);
				emojicons_button.setBackgroundResource(R.drawable.keyboard);
			}

			break;
		case R.id.share_info:
			emojicons_linear.setVisibility(View.GONE);
			emojicons_button.setBackgroundResource(R.drawable.emoji);
			mHlvCustomListWithDividerAndFadingEdge.setVisibility(View.VISIBLE);
			explain_relative.setVisibility(View.VISIBLE);
			break;
		case R.id.share:
			share.setEnabled(false);
			// startProgressDialog();
			if (TextUtils.isEmpty(MessageId)) {

				if (null != messageId && !TextUtils.isEmpty(messageId)) {

					uploadInfo(messageId);
				} else {

					uploadInfo("0");
				}

			} else {

				uploadInfo(MessageId);
			}

			break;

		case R.id.location:
			intent = new Intent(AddMyShareActivity.this, ChooseMyLocationActivity.class);
			startActivityForResult(intent, LOCATION);
			break;

		default:
			break;
		}

	}

	// 搜索列表adapter
	class DataAdapter extends BaseAdapter {

		private Activity activity;
		private LayoutInflater inflater;
		private ViewHolder viewHolder = null;
		private LinkedList<LocationDetail> resultList;

		DataAdapter(Activity activity) {

			inflater = LayoutInflater.from(activity);
			resultList = new LinkedList<LocationDetail>();
		}

		public void addItemLast(List<LocationDetail> datas) {
			resultList.addAll(datas);
		}

		public void addItemTop(List<LocationDetail> datas) {
			resultList.clear();
			for (LocationDetail info : datas) {
				resultList.add(info);
			}
		}

		@Override
		public int getCount() {

			return resultList.size();
		}

		@Override
		public Object getItem(int arg0) {

			return resultList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {

			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup arg2) {

			final ViewHolder viewHolder;

			if (view == null) {
				viewHolder = new ViewHolder();
				view = inflater.inflate(R.layout.my_location_list_item, null);
				viewHolder.location_name = (TextView) view.findViewById(R.id.location_name);
				viewHolder.location_address = (TextView) view.findViewById(R.id.location_address);

				view.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) view.getTag();
			}

			// 字体加粗
			TextPaint tp = viewHolder.location_name.getPaint();
			tp.setFakeBoldText(true);
			viewHolder.location_name.setText(resultList.get(position).getName());
			viewHolder.location_address.setText(resultList.get(position).getAddress());

			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					sectionName = resultList.get(position).getName();
					SharedPreferences preferences = getSharedPreferences("my_location", 0);
					address = preferences.getString("address", "");
					sectionCity = address;
					sectionLocation = resultList.get(position).getAddress();
					if (!TextUtils.isEmpty(sectionName)) {
						recommend_name.setText(sectionName);
					}

				}
			});
			return view;
		}

		class ViewHolder {
			TextView location_name, location_address;
		}
	}

	@SuppressWarnings("unchecked")
	private void getLocationInfo(String latitude, String longitude) {

		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("latitude", latitude);
		paramMap.put("longitude", longitude);
		paramMap.put("city", this.address.substring(3, this.address.length() - 1));
		paramMap.put("limit", "20");
		paramMap.put("radius", "3000");
		paramMap.put("keyword", keyword);
		paramMap.put("sort", "7");
		paramMap.put("page", String.valueOf(pageNo));
		paramMap.put("format", "json");
		new HttpGetRequestAsyncTask(AddMyShareActivity.this, apiUrl).execute(paramMap);
	}

	@Override
	public void onSuccess(Object object) {

		stopProgressDialog();

		String result = (String) object;

		Gson gson = new Gson();
		try {
			mLocationDetailBean = gson.fromJson(result, LocationDetailBean.class);
		} catch (Exception e) {
			return;
		}
		if ("OK".equals(mLocationDetailBean.getStatus())) {

			mDataList = mLocationDetailBean.getBusinesses();

			if (mDataList != null) {

				resultList.clear();
				if (mDataList.size() == 0) {
					mXList.setVisibility(View.GONE);

				} else {
					mXList.setVisibility(View.VISIBLE);
					for (LocationDetail bean : mDataList) {
						resultList.add(bean);

					}
					dataAdapter.addItemTop(resultList);
					dataAdapter.notifyDataSetChanged();
				}

				resetXList();

			} else {
				Alert.error(this, "系统异常");
			}
		} else {
			Alert.error(this, "请求失败");
		}

	}

	@Override
	public void onFail(String exception) {

		stopProgressDialog();
		Alert.error(this, "与服务器连接失败，请检查网络");

	}

	/**
	 * 上传分享内容和图片
	 * 
	 * @author Zhao.JQ
	 */
	@SuppressWarnings("unchecked")
	private void uploadInfo(final String uploadInfo_messageId) {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "saveShareNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("content", share_info.getText().toString().trim()));

		params.add(new BasicNameValuePair("messageId", uploadInfo_messageId));
		params.add(new BasicNameValuePair("platMessageId", platMessageId == null ? (ThemeId == null ? "0" : ThemeId)
				: platMessageId));
		params.add(new BasicNameValuePair("sectionName", TextUtils.isEmpty(sectionName) ? recommend_name.getText()
				.toString() : sectionName));
		params.add(new BasicNameValuePair("sectionCity", sectionCity));
		params.add(new BasicNameValuePair("sectionLocation", sectionLocation));
		params.add(new BasicNameValuePair("address", "位置".equals(location.getText().toString().trim()) ? "" : location
				.getText().toString().trim()));
		switch (fileList.size()) {
		case 1:
			params.add(new BasicNameValuePair("picFile1", fileList.get(0).getPath()));
			params.add(new BasicNameValuePair("picFile2", null));
			params.add(new BasicNameValuePair("picFile3", null));
			params.add(new BasicNameValuePair("picFile4", null));
			params.add(new BasicNameValuePair("picFile5", null));
			params.add(new BasicNameValuePair("picFile6", null));
			break;

		case 2:
			params.add(new BasicNameValuePair("picFile1", fileList.get(0).getPath()));
			params.add(new BasicNameValuePair("picFile2", fileList.get(1).getPath()));
			params.add(new BasicNameValuePair("picFile3", null));
			params.add(new BasicNameValuePair("picFile4", null));
			params.add(new BasicNameValuePair("picFile5", null));
			params.add(new BasicNameValuePair("picFile6", null));
			break;

		case 3:
			params.add(new BasicNameValuePair("picFile1", fileList.get(0).getPath()));
			params.add(new BasicNameValuePair("picFile2", fileList.get(1).getPath()));
			params.add(new BasicNameValuePair("picFile3", fileList.get(2).getPath()));
			params.add(new BasicNameValuePair("picFile4", null));
			params.add(new BasicNameValuePair("picFile5", null));
			params.add(new BasicNameValuePair("picFile6", null));
			break;

		case 4:
			params.add(new BasicNameValuePair("picFile1", fileList.get(0).getPath()));
			params.add(new BasicNameValuePair("picFile2", fileList.get(1).getPath()));
			params.add(new BasicNameValuePair("picFile3", fileList.get(2).getPath()));
			params.add(new BasicNameValuePair("picFile4", fileList.get(3).getPath()));
			params.add(new BasicNameValuePair("picFile5", null));
			params.add(new BasicNameValuePair("picFile6", null));
			break;

		case 5:
			params.add(new BasicNameValuePair("picFile1", fileList.get(0).getPath()));
			params.add(new BasicNameValuePair("picFile2", fileList.get(1).getPath()));
			params.add(new BasicNameValuePair("picFile3", fileList.get(2).getPath()));
			params.add(new BasicNameValuePair("picFile4", fileList.get(3).getPath()));
			params.add(new BasicNameValuePair("picFile5", fileList.get(4).getPath()));
			params.add(new BasicNameValuePair("picFile6", null));
			break;

		case 6:
			params.add(new BasicNameValuePair("picFile1", fileList.get(0).getPath()));
			params.add(new BasicNameValuePair("picFile2", fileList.get(1).getPath()));
			params.add(new BasicNameValuePair("picFile3", fileList.get(2).getPath()));
			params.add(new BasicNameValuePair("picFile4", fileList.get(3).getPath()));
			params.add(new BasicNameValuePair("picFile5", fileList.get(4).getPath()));
			params.add(new BasicNameValuePair("picFile6", fileList.get(5).getPath()));
			break;

		default:
			break;
		}
		params.add(new BasicNameValuePair("tdcId", TdcId == null ? "0" : TdcId));
		params.add(new BasicNameValuePair("sectionId", sectionId == null ? "0" : sectionId));
		new HttpPostRequestAsyncTask(this, new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mMyShareBean = gson.fromJson(result, MyShareBean.class);
				} catch (Exception e) {
					return;
				}
				if (null != mMyShareBean) {
					Intent intent = new Intent();
					// intent.putExtra("shareUrl", mMyShareBean.getLink());
					// intent.putExtra("shareId", mMyShareBean.getShareId());
					// intent.putExtra("messageId", uploadInfo_messageId);

					if (!TextUtils.isEmpty(mMyShareBean.getCoinAlert())) {
						intent.putExtra("has_animation", true);

					}
					share.setEnabled(true);
					Alert.info(AddMyShareActivity.this, "分享成功");
					setResult(RESULT_OK, intent);
					finish();

				} else {
					Alert.warn(AddMyShareActivity.this, result);
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.warn(AddMyShareActivity.this, "与服务器连接失败，请检查网络");

			}
		}, DataStore.class, AppConfig.USER).execute(params);
	}

	private ArrayList<String> getIntentArrayList(ArrayList<String> dataList) {
		pathList.clear();
		for (Bitmap b : this.bitmapList) {
			Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), b, null, null));
			File f = FileProvider.getFileByUri(this, uri);
			pathList.add(f.getPath());
		}
		dataList.clear();
		dataList.addAll(pathList);
		return dataList;

	}

	/**
	 * 获得水印
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void queryPlat() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryPlatMsgAndNew2")); // 添加要传递的参数
		params.add(new BasicNameValuePair("pmId", TextUtils.isEmpty(ThemeId) ? "0" : ThemeId));
		params.add(new BasicNameValuePair("shareFlag", TextUtils.isEmpty(String.valueOf(shareFlag)) ? "0" : String
				.valueOf(shareFlag)));
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;
				Gson gson = new Gson();
				// 被禁言
				if ("1".equals(result)) {

					Alert.warn(AddMyShareActivity.this, "由于多次被举报，您已经被禁言！");
					finish();
				} else {
					try {
						mPlatMessageBean = gson.fromJson(result, PlatMessageBean.class);
					} catch (Exception e) {
						return;
					}
					if (null != mPlatMessageBean) {
						if (mPlatMessageBean.getDesTitle() == null && mPlatMessageBean.getDesContent() == null) {
							explain_relative.setVisibility(View.INVISIBLE);
						} else {
							explain_title.setText(mPlatMessageBean.getDesTitle());
							explain.setText(mPlatMessageBean.getDesContent());
						}

						if (null != mPlatMessageBean.getPlatMessageArr()
								&& !"".equals(mPlatMessageBean.getPlatMessageArr())) {
							Type type = new TypeToken<List<PlatMessageBean>>() {
							}.getType();
							Gson gson1 = new Gson();
							Object fromJson1 = gson1.fromJson(mPlatMessageBean.getPlatMessageArr(), type);
							try {
								mPlatMessageBeanList = (List<PlatMessageBean>) fromJson1;
							} catch (Exception e) {

							}
							if (mPlatMessageBeanList.size() == 0) {
								explain_relative.setVisibility(View.INVISIBLE);
								Alert.error(AddMyShareActivity.this, "目前没有平台活动！");
							} else {

								mHlvCustomListWithDividerAndFadingEdge.setVisibility(View.VISIBLE);

							}

							adapter = new CustomArrayAdapter(AddMyShareActivity.this, mPlatMessageBeanList);
							mHlvCustomListWithDividerAndFadingEdge.setAdapter(adapter);
							if (isRelate != null) {
								isCheck = true;
								platMessageId = mPlatMessageBeanList.get(0).getPlatMessageId();
								CustomArrayAdapter.isSelected.put(0, true);
							}
							mHlvCustomListWithDividerAndFadingEdge.setOnItemClickListener(new OnItemClickListener() {
								@Override
								public void onItemClick(final AdapterView<?> arg0, final View view, final int position,
										final long arg3) {
									Holder vHollder = (Holder) view.getTag();
									if (isCheck) {
										if (CustomArrayAdapter.isSelected.get(position)) {
											CustomArrayAdapter.isSelected.put(position, false);
											vHollder.choose.setChecked(false);
											checkPositionPlat = -1;
											isCheck = false;
											platMessageId = "0";
										} else {
											CustomArrayAdapter.isSelected.put(checkPositionPlat, false);
											vHollder.choose.setChecked(true);
											CustomArrayAdapter.isSelected.put(position, true);
											checkPositionPlat = position;
											platMessageId = mPlatMessageBeanList.get(position).getPlatMessageId();
											adapter.notifyDataSetChanged();

										}

									} else {
										platMessageId = mPlatMessageBeanList.get(position).getPlatMessageId();
										isCheck = true;
										vHollder.choose.setChecked(true);
										boolean check = vHollder.choose.isChecked();
										checkPositionPlat = position;
										CustomArrayAdapter.isSelected.put(position, check);

									}

								}
							});

						}

					} else {
						stopProgressDialog();
						Alert.error(AddMyShareActivity.this, "系统异常");
					}
				}

			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.error(AddMyShareActivity.this, "与服务器连接失败，请检查网络");

			}
		}, PlatMessageBean.class, AppConfig.USER).execute(params);
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == AddMyShareActivity.PICK) {
			if (resultCode != Activity.RESULT_OK) {
				rFilePicture = null;
				return;
			}

			/* rFilePicture值为null表明是从相册挑选。 */
			if (rFilePicture == null) {
				rFilePicture = FileProvider.getFileByUri(this, data.getData());
			}
			mListImageFile.add(rFilePicture.getPath());
			List<Bitmap> bpList = new ArrayList<Bitmap>();
			try {
				Bitmap bitmap = ThumbnailUtils.extractThumbnail(Bimp.revitionImageSize(mListImageFile.get(0)), 240,
						240, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
				int pictureDegree = BitMapUtil.readPictureDegree(mListImageFile.get(0));
				bitmapList.add(BitMapUtil.rotaingImageView(pictureDegree, bitmap));

				bpList.add(BitMapUtil.rotaingImageView(pictureDegree,
						BitMapUtil.getBitmapFromFile(rFilePicture, 1280, 1280)));
				ByteArrayOutputStream myStream = new ByteArrayOutputStream();
				// 压缩质量
				bpList.get(0).compress(Bitmap.CompressFormat.JPEG, 90, myStream);

				byte[] myCopybyte = myStream.toByteArray();

				fileList.add(BitMapUtil.getFileFromBytes(myCopybyte, FileProvider.getNewTemporaryFile()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			mGrideView.setVisibility(View.VISIBLE);
			mGridViewAdapter.setBitmapList(bitmapList);
			mGridViewAdapter.notifyDataSetChanged();
			rFileTemporary = null;
			mListImageFile.clear();

			rFilePicture = null;
		} else if (requestCode == 0) {
			if (resultCode == RESULT_OK) {

				ArrayList<String> tDataList = Bimp.drr;
				if (tDataList != null && tDataList.size() > 0) {
					mGrideView.setVisibility(View.VISIBLE);
					dataList.clear();
					dataList.addAll(tDataList);
					this.bitmapList.clear();
					// upLoadPicList.clear();
					List<Bitmap> bpList = new ArrayList<Bitmap>();
					fileList = new ArrayList<File>();
					for (int i = 0; i < dataList.size(); i++) {
						File file = new File(dataList.get(i));

						// TODO 内存溢出
						Bitmap bitmap = ThumbnailUtils.extractThumbnail(BitMapUtil.getSuitableBitmap(file), 240, 240,
								ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
						int pictureDegree = BitMapUtil.readPictureDegree(file.getPath());
						this.bitmapList.add(BitMapUtil.rotaingImageView(pictureDegree, bitmap));

						bpList.add(BitMapUtil.rotaingImageView(pictureDegree,
								(BitMapUtil.getBitmapFromFile(file, 1280, 1280))));
						try {

							ByteArrayOutputStream myStream = new ByteArrayOutputStream();
							// 压缩质量
							bpList.get(i).compress(Bitmap.CompressFormat.JPEG, 90, myStream);

							byte[] myCopybyte = myStream.toByteArray();

							fileList.add(BitMapUtil.getFileFromBytes(myCopybyte, FileProvider.getNewTemporaryFile()));

						} catch (IOException e) {

							e.printStackTrace();
						}

					}

					// upLoadPicList.addAll(bpList);
					mGridViewAdapter.setBitmapList(this.bitmapList);
					mGridViewAdapter.notifyDataSetChanged();
				}
			}
		} else if (requestCode == 2) {
			if (resultCode == RESULT_OK) {
				setResult(RESULT_OK);
				finish();
			}
		} else if (requestCode == LOCATION) {
			if (null != data) {
				location.setText(data.getStringExtra("location"));
			}

		}
	}

	/**
	 * 获得活动
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void getOrderMsg() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryOrderMsgNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;
				Gson gson = new Gson();
				try {
					mOrderMessageBean = gson.fromJson(result, OrderMessageBean.class);
				} catch (Exception e) {
					return;
				}
				if (null != mOrderMessageBean) {
					isGroupCheck = false;
					if (null != mOrderMessageBean.getRelateMessageArr()
							&& !"".equals(mOrderMessageBean.getRelateMessageArr())) {
						Type type = new TypeToken<List<OrderMessageBean>>() {
						}.getType();
						Gson gson1 = new Gson();
						Object fromJson1 = gson1.fromJson(mOrderMessageBean.getRelateMessageArr(), type);
						try {
							mOrderMessageBeanList = (List<OrderMessageBean>) fromJson1;
						} catch (Exception e) {

						}
						if (mOrderMessageBeanList.size() == 0) {
							isGroupVisibale();
							second_explain_relative.setVisibility(View.INVISIBLE);
							share_HorizontalListView.setVisibility(View.GONE);
						} else {
							isGroupVisibale();
							second_explain_title.setText(mOrderMessageBean.getRmTitle());
							second_explain.setText(mOrderMessageBean.getRmContent());
						}
						mAddShareGroupAdapter = new AddShareGroupAdapter(AddMyShareActivity.this, mOrderMessageBeanList);
						share_HorizontalListView.setAdapter(mAddShareGroupAdapter);
						share_HorizontalListView.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(final AdapterView<?> arg0, final View view, final int position,
									final long arg3) {
								ViewHolder viewHolder = (ViewHolder) view.getTag();
								if (isGroupCheck) {
									if (AddShareGroupAdapter.isSelected.get(position)) {
										viewHolder.choose.setChecked(false);
										AddShareGroupAdapter.isSelected.put(position, false);
										messageId = "0";
										isGroupCheck = false;
									} else {
										AddShareGroupAdapter.isSelected.put(checkPosition, false);
										viewHolder.choose.setChecked(true);
										AddShareGroupAdapter.isSelected.put(position, true);
										checkPosition = position;
										messageId = mOrderMessageBeanList.get(position).getMessageId();
										mAddShareGroupAdapter.notifyDataSetChanged();
									}

								} else {
									messageId = mOrderMessageBeanList.get(position).getMessageId();
									isGroupCheck = true;
									checkPosition = position;
									viewHolder.choose.setChecked(true);
									boolean check = viewHolder.choose.isChecked();
									AddShareGroupAdapter.isSelected.put(position, check);

								}

							}
						});

					}

				} else {
					stopProgressDialog();
					Alert.error(AddMyShareActivity.this, "系统异常");
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.error(AddMyShareActivity.this, "与服务器连接失败，请检查网络");

			}
		}, PlatMessageBean.class, AppConfig.USER).execute(params);
	}

	public boolean dispatchKeyEvent(KeyEvent event) {

		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getRepeatCount() == 0) {
			if (share.getVisibility() == View.VISIBLE) {
				isWatermarkVisibale();
				recommend_name_relative.setVisibility(View.GONE);
				shop.setVisibility(View.GONE);

				if (mPlatMessageBeanList.size() == 0) {
					explain_relative.setVisibility(View.INVISIBLE);
				} else {
					explain_relative.setVisibility(View.VISIBLE);
					explain_title.setText(mPlatMessageBean.getDesTitle());
					explain.setText(mPlatMessageBean.getDesContent());
				}

			} else {
				imm.hideSoftInputFromWindow(share_info.getWindowToken(), 0);
				finish();
			}

			return false;
		} else {
			return super.dispatchKeyEvent(event);
		}
	}

	protected void resetXList() {

		mXList.setRefreshTime(new SimpleDateFormat("H:mm", Locale.CHINA).format(new Date()));
		mXList.stopRefresh();
		mXList.stopLoadMore();
	}

	@Override
	public void onEmojiconClicked(Emojicon emojicon) {
		EmojiconsFragment.input(share_info, emojicon);
	}

	@Override
	public void onEmojiconBackspaceClicked(View v) {
		EmojiconsFragment.backspace(share_info);
	}

}
